import requests
from dotenv import load_dotenv
import os
import re

load_dotenv()
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"


def process_text(text: str) -> str:
    """
    文本处理函数
    """
    print(f"[处理线程] 正在处理文本: {text}")
    # result = requests.get("http://localhost:5000/voice?msg={}".format(text))
    # print(result.text)

    result = call_deepseek_api(text)
    # 模拟返回处理结果
    # result = text
    print(f"[处理线程] 处理完成，结果: {result}")
    return result




def call_deepseek_api(prompt):
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }

    payload = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "system", "content": "请用一段话回答，不要分点，不要用*#等符号，控制在100字以内。"},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7,
        "max_tokens": 100,
        "stop": ["。", "！", "？"]
    }

    response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)

    if response.status_code == 200:
        reply = response.json()["choices"][0]["message"]["content"]

        # 清理特殊符号
        cleaned_reply = re.sub(r'[*#·•]', '', reply)

        # 强制截断到100字（防止API没遵守限制）
        final_reply = cleaned_reply[:100]

        # 确保是一段话（去掉换行符）
        final_reply = final_reply.replace("\n", " ").strip()

        return final_reply
    else:
        raise Exception(f"API请求失败: {response.status_code}, 错误: {response.text}")


